package com.huangwei.websocket.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static ChannelGroup userChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static ChannelGroup adminChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String s = msg.text();
        System.out.println(s);
        userChannels.writeAndFlush(new TextWebSocketFrame(s));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        if (adminChannels.size() == 0) {
            adminChannels.add(ctx.channel());
        } else {
            userChannels.add(ctx.channel());
        }
        adminChannels.writeAndFlush(new TextWebSocketFrame("" + userChannels.size()));
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        userChannels.remove(ctx.channel());
        adminChannels.writeAndFlush(new TextWebSocketFrame("" + userChannels.size()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
